import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import { FormattedMessage } from 'umi-plugin-react/locale';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import PageLoading from '@/components/PageLoading';
import {
  Card,
  Button,
  Icon,
  Modal,
  message,
  Form,
  Input,
  Checkbox,
  Col,
  Row,
  Tag,
  Select,
  Radio,
} from 'antd';
import styles from './index.less';

const SlotSelect = React.lazy(() => import('../Slot/index'));
const OptionsEle = React.lazy(() => import('../Options/index'));
const { Option } = Select;
const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 20 },
};

class SlotCase extends Component {
  constructor(props) {
    super(props);
    this.state = {
      caseArr: props.caseArr,
      slots: props.data,
      selectedSlots: props.selected,
    };
  }

  delCaseItem = index => {
    const { caseArr } = this.props;
    caseArr.splice(index, 1);
    this.props.upDateCase(caseArr);
  };

  forMap = (caseItem, index) => {
    const { dialogSlots, selected } = this.props;
    const { selectedSlots } = this.props;
    const CaseElem = caseItem.caseItemGroups.map((items, itemIndex) =>
      this.forMapItemCase(items, itemIndex, index, caseItem)
    );
    const OptionEles = caseItem.options.map((optionsItem, itemIndex) =>
      this.forMapOptionItem(optionsItem, itemIndex, index)
    );
    const newIndex = index + 1;
    return (
      <Card
        title={`情况${newIndex}`}
        key={index}
        bordered
        className={styles.caseItem}
        extra={<Icon type="close" onClick={() => this.delCaseItem(index)} />}
      >
        <Row>{CaseElem}</Row>
        <div>
          <Form.Item {...formItemLayout} label="询问动作" style={{ marginBottom: 0 }}>
            <SlotSelect
              paramType="obj"
              slots={caseItem.slotsList}
              dialogSlots={dialogSlots}
              upData={(val, index1) => this.addSlotList(val, index1, index)}
              selected={caseItem.slotsList}
              upSelected={(arr, index1) => this.upSelectedData(arr, index1, index)}
            />
          </Form.Item>
          <Form.Item {...formItemLayout} label="询问话术" style={{ marginBottom: 0 }}>
            <Input
              placeholder="请输入询问话术"
              onChange={e => this.fixInquire(e, index)}
              value={caseItem.inquire}
              maxLength={100}
            />
          </Form.Item>
          <Form.Item
            {...formItemLayout}
            label="附加选项"
            style={{ marginBottom: 0 }}
            rule={[{ required: true }]}
          >
            <Radio.Group
              name="radiogroup"
              defaultValue="auto"
              onChange={e => this.fixRadio(e, index)}
              value={caseItem.radio}
            >
              <Radio value="auto">自动</Radio>
              <Radio value="customize">自定义选项</Radio>
            </Radio.Group>
          </Form.Item>
          {caseItem.radio === 'customize' ? (
            <Form.Item {...formItemLayout} style={{ marginBottom: 0 }}>
              <Row style={{ width: 500 }}>
                {OptionEles}
                <Button
                  htmlType="button"
                  type="primary"
                  size="small"
                  onClick={() => this.addOptions(index)}
                  className={styles.addCaseItem}
                >
                  添加
                </Button>
              </Row>
            </Form.Item>
          ) : (
            ''
          )}
        </div>
      </Card>
    );
  };

  forMapItemCase = (items, itemIndex, index, caseItem) => {
    switch (items.itemType) {
      case undefined:
        // return items.map((commItem,commItemIndex)=>this.forMapCommCase(commItem,commItemIndex,itemIndex,index,items,caseItem));
        return (
          <div>
            {items.map((commItem, commItemIndex) =>
              this.forMapCommCase(commItem, commItemIndex, itemIndex, index, items, caseItem)
            )}
            {itemIndex === caseItem.caseItemGroups.length - 1 ? (
              <Button
                htmlType="button"
                type="primary"
                size="small"
                onClick={() => this.addGroupCase(itemIndex, index)}
                className={styles.addGroupItem}
              >
                添加条件组
              </Button>
            ) : (
              ''
            )}
          </div>
        );
      default:
        return this.forMapSpecialCase(items, itemIndex);
    }
  };

  forMapCommCase = (commItem, commItemIndex, itemIndex, index, items, caseItem) => {
    switch (commItem.itemType) {
      case 'slot':
        return this.renderSlotCase(commItem, commItemIndex, itemIndex, index, items, caseItem);
      default:
        return this.renderLogicCase(commItem);
    }
  };

  forMapSpecialCase = (specialItem, specialItemIndex) => {
    return (
      <div key={specialItemIndex}>
        <div className={styles.orItem}>或</div>
      </div>
    );
  };

  renderSlotCase = (slotItem, slotIndex, itemIndex, index, items, caseItem) => {
    const { dialogSlots } = this.props;
    const OptionElem = dialogSlots.map(this.forMapSlotsOption);
    return (
      <Row key={slotIndex}>
        <Col style={{ marginLeft: 30 }}>
          <Select
            defaultValue="none"
            value={slotItem.slotsId}
            className={styles.selectItem}
            onChange={e => this.onSlotOnChange(e, slotItem, slotIndex, itemIndex, index, 'slotsId')}
          >
            <Option value="none">请选择</Option>
            {OptionElem}
          </Select>
          <span className={styles.selectItem}>状态为</span>
          <Select
            defaultValue="unfilled"
            value={slotItem.operator}
            className={styles.selectItem}
            onChange={e =>
              this.onSlotOnChange(e, slotItem, slotIndex, itemIndex, index, 'operator')
            }
          >
            <Option value="filled">已填充</Option>
            <Option value="unfilled">未填充</Option>
          </Select>
          <Icon
            type="close-circle"
            onClick={() => this.delCaseItemByCloseIcon(slotItem, slotIndex, itemIndex, index)}
            style={{ marginLeft: 5, cursor: 'pointer' }}
          />
        </Col>
        <Col style={{ marginLeft: 30 }}>
          {slotIndex === items.length - 1 ? (
            <span
              className={styles.addOneCase}
              onClick={() => this.addOnecase(slotItem, slotIndex, itemIndex, index)}
            >
              {' '}
              <Icon type="plus" />
              添加条件
            </span>
          ) : (
            ''
          )}
        </Col>
        {/* <Col>
          {
            itemIndex === caseItem.caseItemGroups.length-1? <Button htmlType='button' type="primary" size='small' onClick={()=>this.addGroupCase(slotItem,slotIndex,itemIndex,index)} className={styles.addGroupItem}>添加条件组</Button>:''
          }
        </Col>*/}
      </Row>
    );
  };

  forMapSlotsOption = option => {
    return (
      <Option key={option.slotId} value={option.slotId}>
        #{option.slotName}#
      </Option>
    );
  };

  renderLogicCase = (logicItem, logicIndex) => {
    return (
      <div key={logicIndex} className={styles.andItem}>
        且
      </div>
    );
  };

  addCase = () => {
    const { caseArr } = this.props;
    caseArr.push({
      caseItemGroups: [
        [
          {
            itemType: 'slot',
            operator: 'unfilled',
            slotsId: 'none',
            values: [],
          },
        ],
      ],
      slotsList: [],
      radio: 'auto',
      inquire: '',
      action: 'inquire',
      options: [],
    });
    this.props.upDateCase(caseArr);
  };

  upDataByCallBack = res => {
    let { caseArr } = this.props;
    caseArr = res;
    this.props.upNewData(caseArr);
  };

  upSelectedData = (res, index1, index) => {
    const { caseArr } = this.props;
    caseArr[index].slotsList[index1] = res;
    this.props.upNewData(caseArr);
  };

  addSlotList = (res, index1, index) => {
    const { caseArr } = this.props;
    caseArr[index].slotsList[index1] = res;
    this.props.upNewData(caseArr);
  };
  /*
   * item 当前对象
   * index 当前对象所在数组索引
   * itemIndex 当前数组所在二维数组索引
   * rootIndex 循环根index
   * */
  addOnecase = (item, slotIndex, itemIndex, rootIndex) => {
    const { caseArr } = this.props;
    caseArr[rootIndex].caseItemGroups[itemIndex].push({
      itemType: 'logic',
      value: 'and',
    });
    caseArr[rootIndex].caseItemGroups[itemIndex].push({
      itemType: 'slot',
      operator: 'unfilled',
      slotsId: 'none',
      values: [],
    });
    this.upDataByCallBack(caseArr);
  };

  addGroupCase = (itemIndex, rootIndex) => {
    const { caseArr } = this.props;
    caseArr[rootIndex].caseItemGroups.push({
      itemType: 'logic',
      value: 'or',
    });
    caseArr[rootIndex].caseItemGroups.push([
      {
        itemType: 'slot',
        operator: 'unfilled',
        slotsId: 'none',
        values: [],
      },
    ]);
    this.upDataByCallBack(caseArr);
  };

  delCaseItemByCloseIcon = (item, slotIndex, itemIndex, rootIndex) => {
    const { caseArr } = this.props;
    if (slotIndex === 0 && itemIndex === 0 && rootIndex === 0) {
      // caseArr[rootIndex].caseItemGroups[itemIndex].splice(slotIndex,1);

      return false;
    }

    if (caseArr[rootIndex].caseItemGroups[itemIndex].length > 1) {
      if (slotIndex === 0) {
        if (caseArr[rootIndex].caseItemGroups[itemIndex][slotIndex + 1].itemType !== undefined) {
          caseArr[rootIndex].caseItemGroups[itemIndex].splice(slotIndex, 1);
          caseArr[rootIndex].caseItemGroups[itemIndex].splice(slotIndex, 1);
        }
      } else {
        if (caseArr[rootIndex].caseItemGroups[itemIndex][slotIndex - 1].itemType !== undefined) {
          caseArr[rootIndex].caseItemGroups[itemIndex].splice(slotIndex, 1);
          caseArr[rootIndex].caseItemGroups[itemIndex].splice(slotIndex - 1, 1);
        }
      }
    } else {
      if (caseArr[rootIndex].caseItemGroups[itemIndex - 1].itemType !== undefined) {
        caseArr[rootIndex].caseItemGroups[itemIndex].splice(slotIndex, 1);
        caseArr[rootIndex].caseItemGroups.splice(itemIndex - 1, 1);
      }
    }
    this.upDataByCallBack(caseArr);
  };

  onSlotOnChange = (e, slotItem, slotIndex, itemIndex, index, type) => {
    const { caseArr } = this.props;
    caseArr[index].caseItemGroups[itemIndex][slotIndex][type] = e;
    this.upDataByCallBack(caseArr);
  };

  fixInquire = (val, index) => {
    const { caseArr } = this.props;
    caseArr[index].inquire = val.target.value;
    this.upDataByCallBack(caseArr);
  };

  fixRadio = (val, index) => {
    const { caseArr } = this.props;
    caseArr[index].radio = val.target.value;
    this.upDataByCallBack(caseArr);
  };

  forMapOptionItem = (optionsItem, itemIndex, index) => {
    return (
      <Col span={8} gutter={10} key={itemIndex}>
        <span>
          <span className={styles.slotNumber}>{itemIndex + 1}</span>
          <Input
            placeholder=""
            style={{ width: 120 }}
            value={optionsItem}
            maxLength={20}
            defaultValue=""
            onChange={e => this.UpdateOption(e, itemIndex, index)}
          />
          <Icon
            type="close-circle"
            style={{ marginLeft: 5, cursor: 'pointer' }}
            onClick={() => this.delOptionsByIndex(itemIndex, index)}
          />
        </span>
      </Col>
    );
  };

  addOptions = index => {
    const { caseArr } = this.props;
    caseArr[index].options.push('');
    this.upDataByCallBack(caseArr);
  };

  delOptionsByIndex = (itemIndex, index) => {
    const { caseArr } = this.props;
    caseArr[index].options.splice(itemIndex, 1);
    this.upDataByCallBack(caseArr);
  };

  UpdateOption = (e, itemIndex, index) => {
    const { caseArr } = this.props;
    caseArr[index].options[itemIndex] = e.target.value;
    this.upDataByCallBack(caseArr);
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { caseArr } = this.props;
    const CaseChild = caseArr.map((item, index) => this.forMap(item, index));
    return (
      <GridContent>
        <Suspense fallback={<PageLoading />}>
          {CaseChild}
          <div className={styles.caseItem}>
            <Button
              htmlType="button"
              type="primary"
              size="small"
              onClick={() => this.addCase()}
              className={styles.addCaseItem}
            >
              添加情况
            </Button>
          </div>
        </Suspense>
      </GridContent>
    );
  }
}
export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(SlotCase));
